import { think } from 'thinkjs';

// import RestModelClass, { RestOption } from "src/types/utils/rest";
import Base, { ServiceOption } from '../../../../../service/base';
import { IUser } from '../../types';
import {
  IServiceCloudImUserCreateParams,
  IServiceCloudImUserCreateResult,
  IServiceCloudImUserFetchParams,
  IServiceCloudImUserFetchResult,
  IServiceCloudImUserUpdateParams,
  IServiceCloudImUserUpdateTokenParams,
  IServiceCloudImUserUpdateTokenResult,
} from '../../types/service/User';
import mongo from '../../../../../utils/mongo';
import mongoose from 'mongoose';
import { SchemaUser } from '../../types/model/User';
import { syncValidate } from '../../../../utils/validate';

export default class extends Base<IUser> {
  constructor(option: ServiceOption) {
    super(option);
  }

  /**
   * 创建云通信ID
   */
  async create(params: IServiceCloudImUserCreateParams): Promise<IServiceCloudImUserCreateResult> {
    await syncValidate(params, {
      account: {
        required: true,
      },
    });
    const { account } = params;
    const token = think.md5(account + '' + Date.now());
    const UserModel = mongo.model('user', SchemaUser);
    const existUser = await UserModel.findOne({
      account,
    });
    console.log('[existUser] ', existUser);
    if (!think.isEmpty(existUser)) throw new Err('account 重复');
    const user = new UserModel({
      ...params,
      token,
    });
    let { _id } = await user.save();
    if (think.isEmpty(_id)) {
      throw new Err('创建失败');
    }
    return {
      account,
      token,
    };
  }

  async updateToken(params: IServiceCloudImUserUpdateTokenParams): Promise<IServiceCloudImUserUpdateTokenResult> {
    await syncValidate(params, {
      account: {
        required: true,
      },
    });
    const { account } = params;
    const token = think.md5(account + '' + Date.now());
    const UserModel = mongo.model('user', SchemaUser);
    let { nModified } = await UserModel.update(
      {
        account,
      },
      {
        token,
      },
    );
    if (nModified === 0) throw new Err('更新失败，请检查参数');
    return {
      account,
      token,
    };
  }

  async fetch({ accounts, currentPage, pageSize }: IServiceCloudImUserFetchParams): Promise<IServiceCloudImUserFetchResult> {
    const UserModel = mongo.model<IUser & mongoose.Document>('user', SchemaUser);
    let where = {
      account: {
        $in: accounts,
      },
    };
    const users = await UserModel.find(where)
      .skip((currentPage - 1) * pageSize)
      .limit(pageSize)
      .exec();
    return {
      users,
    };
  }

  /**
   * 更新IM个人名片
   */
  async updateUinfo(params: IServiceCloudImUserUpdateParams): Promise<'ok'> {
    await syncValidate(params, {
      account: {
        required: true,
      },
      token: {
        required: true
      }
    });
    const { account, token, ...data } = params;
    const UserModel = mongo.model('user', SchemaUser);
    let { nModified } = await UserModel.update(
      {
        account,
      },
      {
        ...data,
        updateTime: Date.now()
      },
    );
    if (nModified === 0) throw new Err('更新失败，请检查参数');
    return 'ok';
  }

}
